"""
Case Type   : dolphin
Case Name   : 未加载插件时连接B库，合理报错
Create At   : 2024.09.23
Owner       : @zhanghuan96
Description :
    1、创建兼容b库和用户
    2、使用新创建的用户连接B库
    3、清理环境
Expect      :
    1、成功
    2、合理报错
    3、清理成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class CompatibilityTest01(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.sh_pri = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.db_name = 'db_dolphin_0029'
        self.user_name = 'user_dolphin_0029'

    def test_create_function(self):
        text = '-----step1:创建兼容b库和用户;expect:成功-----'
        self.log.info(text)
        sql_cmd = (f"drop database if exists {self.db_name};"
                   f"create database {self.db_name} dbcompatibility ='B';"
                   f"drop user if exists {self.user_name};"
                   f"create user {self.user_name} with sysadmin "
                   f"identified by '{macro.COMMON_PASSWD}';")
        self.log.info(sql_cmd)
        sql_res = self.sh_pri.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertEqual(1,
                         sql_res.count(self.constant.CREATE_DATABASE_SUCCESS),
                         '兼容B库创建失败')
        self.assertIn('CREATE ROLE', sql_res, '创建失败')

        text = '-step2:使用新创建的用户连接B库;expect:合理报错-'
        self.log.info(text)
        cmd3 = "select version();"
        self.log.info(cmd3)
        res3 = self.sh_pri.execut_db_sql(sql=cmd3,
                                         sql_type=f'-U {self.user_name} '
                                                  f'-W {macro.COMMON_PASSWD}',
                                         dbname=self.db_name)
        self.log.info(res3)
        self.assertIn('FATAL:  Please use the original role to '
                      'connect B-compatibility database first',
                      res3, '创建失败')

    def tearDown(self):
        text = '-----step3:清理环境;expect:成功-----'
        self.log.info(text)
        sql_cmd4 = f"drop database if exists {self.db_name};"
        self.log.info(sql_cmd4)
        sql_res4 = self.sh_pri.execut_db_sql(sql_cmd4, dbname='postgres')
        self.log.info(sql_res4)
        sql_cmd5 = f"drop user if exists {self.user_name};"
        self.log.info(sql_cmd5)
        sql_res5 = self.sh_pri.execut_db_sql(sql_cmd5)
        self.log.info(sql_res5)
        self.assertEqual(1,
                         sql_res4.count(self.constant.DROP_DATABASE_SUCCESS),
                         '清理环境失败')
        self.assertIn('DROP ROLE', sql_res5)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
